# SSL修复 - 必须在其他网络库导入之前执行
import sys
import json
import requests
import webbrowser
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, 
    QPushButton, QScrollArea, QFrame, QTextEdit, QTabWidget, QListWidget,
    QListWidgetItem, QGridLayout, QProgressBar, QTableWidget, QTableWidgetItem, QMessageBox,
    QDialog, QSizePolicy
)
from PyQt5.QtCore import Qt, pyqtSignal, QObject, QThread, QEvent, QUrl
from PyQt5.QtGui import QPixmap, QFont, QColor, QImage, QMouseEvent, QPainter, QClipboard

# 全局图片缓存
_image_cache = {}
_image_cache_max_size = 500
# 全局加载状态记录
_loading_urls = set()

# 简单详情缓存（避免重复请求同一商品）
_detail_cache = {}

# 商品详情API通信类
class ProductDetailAPI(QObject):
    data_received = pyqtSignal(dict)
    error_occurred = pyqtSignal(str)
    progress_log = pyqtSignal(str)
    
    def __init__(self):
        super().__init__()
        self.base_url = "https://app.kwaixiaodian.com/gateway/distribute/match/selection/decision/app/info"
        # 从配置文件加载Cookie
        from config import config
        saved_cookies = config.get("cookies.list", [])
        if saved_cookies:
            self.cookies = saved_cookies
        else:
            # 默认Cookie配置，支持轮换使用
            self.cookies = [
                "__NSWJ=; appver=13.5.10.9282; browseType=4; c=a; cdidTag=2; cdid_tag=2; cl=0; client_key=56c3713c; countryCode=cn; country_code=cn; cs=false; darkMode=false; deviceBit=0; did=56C17D9C-2C3E-75AC-6B29-152CD2DE865D; didTag=0; did_tag=0; egid=DFP2EAFD23086EF95037695D2030C4B93E46DE9D450A8D61F46CDF3C7C9C7D82; foreign=0; ftt=; gid=DFP2EAFD23086EF95037695D2030C4B93E46DE9D450A8D61F46CDF3C7C9C7D82; global_id=DFPFAA7C74495905F5CDA5954851849B205736A325A02715E6DC6C81789801E3; grant_browse_type=AUTHORIZED; isp=; kpf=IPHONE; kpn=KUAISHOU; kuaishou.api_st=Cg9rdWFpc2hvdS5hcGkuc3QSoAFwXEw4FN1sgI31vB16Unjgkz053ZGbGy27APbGRUNVO_BVWi9d8CtugoHQMclxwcC5OGNtwBrCxbFWUXCKNczY8x1KiIiUrc20cBs1g3c8vGX9cCRXdThV_QQXH5TWPmdFjFIFFtuYPPiycVH4ephO9TGqBN1TaUOJ_FgRO0oAR7NLjXCOxi9VaLeRiSDTarTuW1kgEp-M4GsAEgzHZi1uGhJyESpTOl5I_JMcRn3Byf2u1vciIBDcgqpx2hfw691TXmH2-vBKikJ_B3LUOBwnNS9DECh4KAUwAQ; kuaishou.h5_st=Cg5rdWFpc2hvdS5oNS5zdBKgAdDRHj6dpBJcPDwhXo5-ao65mHDwZlXGmT3ZdinIQe2hrN-3kfF7Drv_rWu2XDwSqcbwjOGTHuiBcxkO_fPAN0PYvzAyTY9xCumtsxfSkpqRb6PIZyjm6_JbK-WVZgeeJSa1iMn8_O3ONzKR3oUg6LBgdnZ9tX4ub0DOcUQ376VsFZxK5dzr5NcH3DaTr7L3zDp3uFXxpYJbkmJrQ4Z3wb0aErRK2QH7PcRzQqctYBkoxtl-QSIgZGS4uYldJzzf2LDF8wFZYrQvWeErQ_VFg5RLWWRmxywoBTAB; kuaishou.sixin.login_st=ChdrdWFpc2hvdS5zaXhpbi5sb2dpbi5zdBKgAQIPDUeKOrnZWOy3YIFQOciuG1s7P_MTpUud7JXTvzDnue6RXp-QOFverMA-w6rPzlY1cPdQtEwBj-wn4vbWAx_VbwlSQXMWU77hUthnlg8-KQebqVEjm3Y4fL17iW3YiC8xTX5gtVQD3GuLBMcJvQ-lRozc-QFFlLriPki2mttGhL_o0f1006NFJtqc_ZJGRZmxgm0kTrW79fFrIhprNPgaEiX5bz-J70ThowsWD80kXuYL-yIgwtE3YJD29lsbpkXt7mWHdLCY_5ZnRT5DzAZ8P5e9gYAoBTAB; language=zh-Hans%3Bq%3D1%2C%20en%3Bq%3D0.9; lat=; lkvr=; ll=; ll_client_time=0; lon=; mcc=; mod=iPhone9%2C4; net=WIFI; oDid=6505F793-D877-43C9-9778-CA597F84DDDE; odid=6505F793-D877-43C9-9778-CA597F84DDDE; os=15.8.4; power_mode=0; randomDid=6505F793-D877-43C9-9778-CA597F84DDDE; rdid=6505F793-D877-43C9-9778-CA597F84DDDE; session_id=98BCD746-5A17-44EB-9937-4B6F1E32780A; sh=2208; sid=98BCD746-5A17-44EB-9937-4B6F1E32780A; sw=1242; sys=iOS_15.8.4; thermal=10000; token=77184c1fce0645c9a3ef06795cecf76e-3792331592; uQaTag=1%23%23cmWns%3A0-%23swLdgl%3A99%23ecPp%3A8-%23cmNt%3A11; ud=3792331592; urlencode_mod=iPhone9%252C4; userId=3792331592; userRecoBit=0; ver=13.5; videoModelCrowdTag=1_62; weblogger_switch="
            ]
        self.current_cookie_index = 0  # 当前使用的Cookie索引
        self.headers = {
            "Host": "app.kwaixiaodian.com",
            "usern": "1",
            "accept": "application/json, text/plain, */*",
            "kpf": "IPHONE_H5",
            "kpn": "KUAISHOU",
            "accept-language": "zh-CN,zh-Hans;q=0.9",
            "origin": "https://app.kwaixiaodian.com",
            "user-agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 15_8_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 Kwai/13.5.10.9282 MerchantWeb/1.0 ISLP/0 StatusHT/20 KDT/PHONE iosSCH/0 TitleHT/44 NetType/WIFI ISDM/0 ICFO/0 locale/zh-Hans CT/0 Yoda/3.2.6 ISLB/0 CoIS/2 ISLM/0 WebViewType/WK BHT/0 AZPREFIX/az3",
            "referer": "https://app.kwaixiaodian.com/page/kwaishop-cps-selection-decision-app?layoutType=4&relItemId=21505924839280&sceneId=&serverExpTag=",
            "content-type": "application/json",
            "Connection": "keep-alive"
        }
        
    def update_cookies(self, cookies_list):
        """更新Cookie列表"""
        if cookies_list and any(cookie.strip() for cookie in cookies_list):
            # 过滤掉空字符串
            self.cookies = [cookie.strip() for cookie in cookies_list if cookie.strip()]
            self.current_cookie_index = 0
        
    def get_current_cookie(self):
        """获取当前轮换的Cookie"""
        if not self.cookies or len(self.cookies) == 0:
            return ""
        # 确保 cookies 是列表格式
        if isinstance(self.cookies, dict):
            # 如果是字典格式，尝试获取列表
            cookies_list = self.cookies.get('list', [])
            if cookies_list:
                self.cookies = cookies_list
            else:
                return ""
        
        cookie = self.cookies[self.current_cookie_index]
        # 轮换到下一个Cookie
        self.current_cookie_index = (self.current_cookie_index + 1) % len(self.cookies)
        return cookie
        
    def get_product_detail(self, rel_item_id):
        # 添加Cookie到请求头（使用轮换机制）
        headers_with_cookie = self.headers.copy()
        current_cookie = self.get_current_cookie()
        headers_with_cookie["Cookie"] = current_cookie
        # 动态设置 referer 中的 relItemId，避免被风控/校验
        try:
            headers_with_cookie["referer"] = f"https://app.kwaixiaodian.com/page/kwaishop-cps-selection-decision-app?layoutType=4&relItemId={rel_item_id}&sceneId=&serverExpTag="
        except Exception:
            pass
        
        payload = {
            "relItemId": rel_item_id,
            "sceneCode": "selection_decision",
            "themeSceneId": "",
            "relSceneCode": "CPS"
        }
        # 打印请求信息用于调试
        import json
        msg1 = f"[商品详情API请求] 地址: {self.base_url}"
        msg2 = f"[商品详情API请求] 参数: {json.dumps(payload, ensure_ascii=False)}"
        print(msg1)
        print(msg2)
        try:
            self.progress_log.emit(msg1); self.progress_log.emit(msg2)
        except Exception:
            pass
        
        try:
            import requests as R
            s = R.Session()
            s.trust_env = False  # 忽略系统代理，直连
            proxies = {"http": None, "https": None}
            self.progress_log.emit("[商品详情API请求] 开始请求…")
            response = s.post(
                self.base_url,
                headers=headers_with_cookie,
                json=payload,
                timeout=15,
                proxies=proxies,
            )
            self.progress_log.emit(f"[商品详情API响应] 状态码: {response.status_code}")
            if response.status_code == 200:
                data = response.json()
                print(f"[商品详情API响应] 状态: {data.get('result', 'unknown')}")
                print(f"[商品详情API响应] 数据: {json.dumps(data, ensure_ascii=False)[:200]}...")
                if data.get('result') != 1:
                    error_msg = data.get('error_msg', '未知错误')
                    if '登录' in error_msg or 'login' in error_msg.lower() or '失效' in error_msg:
                        self.error_occurred.emit(f"数据获取失败：当前登录失效，请重新登录")
                    else:
                        self.error_occurred.emit(f"数据获取失败：{error_msg}")
                else:
                    self.data_received.emit(data)
            else:
                self.error_occurred.emit(f"请求失败，状态码: {response.status_code}")
        except Exception as e:
            self.error_occurred.emit(f"请求异常: {str(e)}")
            
    def update_cookie(self, new_cookie):
        """更新Cookie值（保持向后兼容）"""
        # 将单个Cookie转换为列表格式
        if new_cookie:
            self.cookies = [new_cookie]
            self.current_cookie_index = 0

# 可点击的标签类
class ClickableLabel(QLabel):
    clicked = pyqtSignal(str)  # 点击信号，传递URL参数
    
    def __init__(self, url=""):
        super().__init__()
        self.url = url
        
    def mousePressEvent(self, ev):
        from PyQt5.QtCore import Qt
        from PyQt5.QtGui import QMouseEvent
        if ev is not None and isinstance(ev, QMouseEvent) and ev.button() == Qt.MouseButton.LeftButton:
            self.clicked.emit(self.url)
        super().mousePressEvent(ev)

# 商品详情窗口
class ProductDetailWindow(QMainWindow):
    def __init__(self, rel_item_id, main_window=None):
        super().__init__()
        self.rel_item_id = rel_item_id
        self.main_window_ref = main_window
        self.api = ProductDetailAPI()
        # 统一使用首页 API 的 Cookie，确保与列表一致
        try:
            if self.main_window_ref is not None and hasattr(self.main_window_ref, 'api'):
                cookies_src = getattr(self.main_window_ref.api, 'cookies', None)
                if cookies_src:
                    self.api.update_cookies(list(cookies_src))
        except Exception:
            pass
        self.api.data_received.connect(self.on_data_received)
        self.api.error_occurred.connect(self.on_error)
        # 将商品详情请求日志输出到主窗口首页日志控制台
        try:
            if self.main_window_ref is not None and hasattr(self.main_window_ref, 'add_log_message'):
                self.api.progress_log.connect(lambda m: self.main_window_ref.add_log_message(m, "#9CA3AF"))
        except Exception:
            pass
        
        # 初始化图片加载器字典
        self._image_loaders = {}
        
        # 存储活动的图片加载线程
        self.active_image_loaders = []
        
        self.setup_ui()
        self.load_product_data()
        
        # 设置窗口总是在最前面显示
        self.setWindowFlags(self.windowFlags() | Qt.WindowType.WindowStaysOnTopHint)
        
    def setup_ui(self):
        self.setWindowTitle("商品详情")
        self.setGeometry(150, 150, 1200, 800)
        
        # 设置整体样式 - 使用柔和、专业的色彩
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f8f9fa;
            }
            QLabel {
                color: #343a40;
            }
        """)
        
        # 中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        main_layout = QVBoxLayout(central_widget)
        main_layout.setSpacing(15)
        main_layout.setContentsMargins(20, 20, 20, 20)
        
        # 滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        main_layout.addWidget(scroll_area)
        
        # 内容部件
        content_widget = QWidget()
        content_widget.setStyleSheet("background-color: white; border-radius: 12px; padding: 20px;")
        scroll_area.setWidget(content_widget)
        
        # 内容布局
        content_layout = QVBoxLayout(content_widget)
        content_layout.setSpacing(20)
        
        # 标题区域 - 移除返回按钮
        title_widget = QWidget()
        title_layout = QHBoxLayout(title_widget)
        title_layout.setContentsMargins(0, 0, 0, 0)
        
        # 标题标签
        self.title_label = QLabel("商品详情加载中...")
        self.title_label.setWordWrap(True)
        self.title_label.setFont(QFont("Arial", 18, QFont.Bold))
        self.title_label.setStyleSheet("color: #212529; padding: 10px 0; border-bottom: 1px solid #e9ecef;")
        title_layout.addWidget(self.title_label)
        title_layout.addStretch()
        
        content_layout.addWidget(title_widget)
        
        # 分割线
        separator = QFrame()
        separator.setFrameShape(QFrame.HLine)
        separator.setStyleSheet("color: #e9ecef;")
        content_layout.addWidget(separator)
        
        # 主要信息区域（图片和基本信息）- 优化布局
        main_info_layout = QHBoxLayout()
        main_info_layout.setSpacing(25)
        
        # 图片区域 - 美化样式
        self.image_container = QWidget()
        self.image_container.setStyleSheet("background-color: #f8f9fa; border-radius: 12px; padding: 15px;")
        image_layout = QVBoxLayout(self.image_container)
        image_layout.setContentsMargins(0, 0, 0, 0)
        image_layout.setSpacing(12)
        
        self.main_image_label = QLabel()
        self.main_image_label.setFixedSize(280, 280)
        self.main_image_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.main_image_label.setStyleSheet("background-color: white; border-radius: 10px; font-size: 16px; color: #6c757d; border: 1px solid #e9ecef;")
        self.main_image_label.setText("主图加载中...")
        image_layout.addWidget(self.main_image_label)
        
        # 缩略图列表
        self.thumbnail_list = QListWidget()
        self.thumbnail_list.setFixedHeight(80)
        self.thumbnail_list.setStyleSheet("background-color: transparent; border: none; outline: 0;")
        self.thumbnail_list.setFlow(QListWidget.LeftToRight)
        self.thumbnail_list.setHorizontalScrollMode(QListWidget.ScrollPerPixel)
        image_layout.addWidget(self.thumbnail_list)
        
        main_info_layout.addWidget(self.image_container)
        
        # 基本信息区域 - 美化样式
        info_container = QWidget()
        info_container.setStyleSheet("background-color: #f8f9fa; border-radius: 12px; padding: 20px;")
        info_layout = QVBoxLayout(info_container)
        info_layout.setSpacing(15)
        
        # 价格信息
        self.price_label = QLabel("价格: ¥--")
        self.price_label.setFont(QFont("Arial", 22, QFont.Bold))
        self.price_label.setStyleSheet("color: #dc3545; padding: 10px 0;")
        info_layout.addWidget(self.price_label)
        
        # 佣金信息容器
        commission_widget = QWidget()
        commission_layout = QHBoxLayout(commission_widget)
        commission_layout.setContentsMargins(0, 0, 0, 0)
        commission_layout.setSpacing(15)
        
        self.commission_label = QLabel("佣金比例: --%")
        self.commission_label.setStyleSheet("color: #0d6efd; font-weight: bold; font-size: 16px; background-color: #e7f1ff; padding: 8px 16px; border-radius: 20px;")
        commission_layout.addWidget(self.commission_label)
        
        self.profit_label = QLabel("赚取: ¥--")
        self.profit_label.setStyleSheet("color: #198754; font-weight: bold; font-size: 16px; background-color: #e6fcf5; padding: 8px 16px; border-radius: 20px;")
        commission_layout.addWidget(self.profit_label)
        
        commission_layout.addStretch()
        info_layout.addWidget(commission_widget)
        
        # 销量信息
        self.sales_label = QLabel("总销量: --")
        self.sales_label.setStyleSheet("color: #0d6efd; font-weight: bold; font-size: 16px; background-color: #e7f1ff; padding: 8px 16px; border-radius: 20px;")
        info_layout.addWidget(self.sales_label)
        
        # 店铺信息
        self.shop_label = QLabel("店铺: --")
        self.shop_label.setStyleSheet("color: #495057; font-size: 16px; padding: 5px 0;")
        info_layout.addWidget(self.shop_label)
        
        # 店铺评分
        self.shop_score_label = QLabel("店铺评分: --")
        self.shop_score_label.setStyleSheet("color: #495057; font-size: 16px; padding: 5px 0;")
        info_layout.addWidget(self.shop_score_label)
        
        info_layout.addStretch()
        main_info_layout.addWidget(info_container)
        main_info_layout.setStretch(0, 1)
        main_info_layout.setStretch(1, 1)
        content_layout.addLayout(main_info_layout)
        
        # 标签页 - 美化样式
        self.tab_widget = QTabWidget()
        self.tab_widget.setStyleSheet("""
            QTabWidget::pane { border: 1px solid #dee2e6; border-radius: 8px; padding: 5px; background-color: white; }
            QTabBar::tab { background: #f8f9fa; border: 1px solid #dee2e6; border-bottom-color: #dee2e6; border-top-left-radius: 6px; border-top-right-radius: 6px; padding: 10px 20px; margin: 3px; color: #495057; font-weight: 500; }
            QTabBar::tab:selected { background: white; border-bottom-color: white; font-weight: bold; color: #0d6efd; }
            QTabBar::tab:hover { background: #e9ecef; }
        """)
        content_layout.addWidget(self.tab_widget)
        
        # 商品详情标签页
        self.detail_tab = QWidget()
        detail_layout = QVBoxLayout(self.detail_tab)
        detail_layout.setSpacing(15)
        
        self.detail_text = QTextEdit()
        self.detail_text.setReadOnly(True)
        self.detail_text.setStyleSheet("border: 1px solid #dee2e6; border-radius: 8px; padding: 20px; background-color: #f8f9fa; color: #343a40; font-size: 15px;")
        detail_layout.addWidget(self.detail_text)
        self.tab_widget.addTab(self.detail_tab, "商品详情")
        
        # 推广数据标签页
        self.promotion_tab = QWidget()
        promotion_layout = QVBoxLayout(self.promotion_tab)
        promotion_layout.setSpacing(15)
        
        self.promotion_text = QTextEdit()
        self.promotion_text.setReadOnly(True)
        self.promotion_text.setStyleSheet("border: 1px solid #dee2e6; border-radius: 8px; padding: 20px; background-color: #f8f9fa; color: #343a40; font-size: 15px;")
        promotion_layout.addWidget(self.promotion_text)
        self.tab_widget.addTab(self.promotion_tab, "推广数据")
        
        # 用户评价标签页
        self.review_tab = QWidget()
        review_layout = QVBoxLayout(self.review_tab)
        review_layout.setSpacing(15)
        
        self.review_list = QListWidget()
        self.review_list.setStyleSheet("border: 1px solid #dee2e6; border-radius: 8px; padding: 15px; background-color: #f8f9fa; color: #343a40;")
        review_layout.addWidget(self.review_list)
        self.tab_widget.addTab(self.review_tab, "用户评价")
        
        # 视频带货标签页
        self.video_tab = QWidget()
        video_layout = QVBoxLayout(self.video_tab)
        video_layout.setSpacing(15)
        
        self.video_list = QListWidget()
        self.video_list.setStyleSheet("border: 1px solid #dee2e6; border-radius: 8px; padding: 15px; background-color: #f8f9fa;")
        self.video_list.setFlow(QListWidget.LeftToRight)
        self.video_list.setWrapping(True)
        self.video_list.setHorizontalScrollMode(QListWidget.ScrollPerPixel)
        video_layout.addWidget(self.video_list)
        self.tab_widget.addTab(self.video_tab, "视频带货")
        
        # 同店推荐标签页
        self.recommend_tab = QWidget()
        recommend_layout = QVBoxLayout(self.recommend_tab)
        recommend_layout.setSpacing(15)
        
        self.recommend_list = QListWidget()
        self.recommend_list.setStyleSheet("border: 1px solid #dee2e6; border-radius: 8px; padding: 15px; background-color: #f8f9fa;")
        self.recommend_list.setFlow(QListWidget.LeftToRight)
        self.recommend_list.setWrapping(True)
        self.recommend_list.setHorizontalScrollMode(QListWidget.ScrollPerPixel)
        recommend_layout.addWidget(self.recommend_list)
        self.tab_widget.addTab(self.recommend_tab, "同店推荐")
        
    def load_product_data(self):
        # 命中缓存直接渲染
        try:
            if self.rel_item_id in _detail_cache:
                self.on_data_received(_detail_cache[self.rel_item_id])
                return
        except Exception:
            pass
        # 后台线程请求，避免阻塞UI（不复用 QObject，直接在线程里发请求，再把结果通过信号带回）
        from PyQt5.QtCore import QThread, pyqtSignal
        class DetailWorker(QThread):
            result = pyqtSignal(dict)
            error = pyqtSignal(str)
            def __init__(self, rid: str, headers: dict, cookie: str, base_url: str):
                super().__init__()
                self.rid = rid
                self.headers = headers
                self.cookie = cookie
                self.base_url = base_url
            def run(self):
                try:
                    import requests as R, json
                    s = R.Session(); s.trust_env = False
                    proxies = {"http": None, "https": None}
                    headers = self.headers.copy()
                    headers["Cookie"] = self.cookie or ""
                    # 动态 referer
                    headers["referer"] = f"https://app.kwaixiaodian.com/page/kwaishop-cps-selection-decision-app?layoutType=4&relItemId={self.rid}&sceneId=&serverExpTag="
                    payload = {"relItemId": self.rid, "sceneCode": "selection_decision", "themeSceneId": "", "relSceneCode": "CPS"}
                    r = s.post(self.base_url, headers=headers, json=payload, timeout=15, proxies=proxies)
                    if r.status_code == 200:
                        self.result.emit(r.json())
                    else:
                        self.error.emit(f"请求失败，状态码: {r.status_code}")
                except Exception as e:
                    self.error.emit(str(e))
        # 取当前 cookie（轮询）
        try:
            current_cookie = self.api.get_current_cookie() if hasattr(self.api, 'get_current_cookie') else ""
        except Exception:
            current_cookie = ""
        self._detail_thread = DetailWorker(self.rel_item_id, self.api.headers, current_cookie, self.api.base_url)
        self._detail_thread.result.connect(self.on_data_received)
        self._detail_thread.error.connect(self.on_error)
        self._detail_thread.start()
        
    def on_data_received(self, data):
        # 检查API响应是否成功
        if data.get("result") != 1:
            self.on_error("数据获取失败: " + data.get("error_msg", "未知错误"))
            return
            
        # 解析商品数据
        data_section = data.get("data", {})
        data_items = data_section.get("data", {})
        
        # 提取商品信息
        item_title = ""
        zk_final_price = ""
        reserve_price = ""
        commission_rate = ""
        profit_amount = ""
        total_sale_amount = ""
        shop_name = ""
        shop_score = ""
        item_img_urls = []
        comments = []
        promote_info = {}
        video_list = []
        top_item_list = []
        tag_list = []
        
        # 查找商品标题
        for key, value in data_items.items():
            if key.startswith("mtp_goodsTitle_") and "fields" in value:
                item_title = value["fields"].get("itemTitle", "")
                tag_list = value["fields"].get("titleTagDto", [])
                break
                
        # 查找价格信息
        for key, value in data_items.items():
            if key.startswith("mtp_priceInfo_") and "fields" in value:
                price_fields = value["fields"]
                zk_final_price = price_fields.get("zkFinalPrice", "")
                reserve_price = price_fields.get("reservePrice", "")
                break
                
        # 查找佣金信息
        for key, value in data_items.items():
            if key.startswith("mtp_commission_") and "fields" in value:
                commission_fields = value["fields"]
                commission_info = commission_fields.get("commission", {})
                commission_rate = commission_info.get("commissionRate", "")
                profit_amount = commission_info.get("profitAmount", "")
                break
                
        # 查找销量信息
        for key, value in data_items.items():
            if key.startswith("mtp_saleInfo_") and "fields" in value:
                sale_fields = value["fields"]
                total_sale_amount = sale_fields.get("totalSaleAmount", "")
                break
                
        # 查找店铺信息
        for key, value in data_items.items():
            if key.startswith("mtp_storeEntrance_") and "fields" in value:
                store_fields = value["fields"]
                shop_info = store_fields.get("shopInfo", {})
                shop_name = shop_info.get("shopName", "")
                store_score_info = shop_info.get("storeScoreInfo", {})
                shop_score = store_score_info.get("score", "")
                break
                
        # 查找图片信息
        for key, value in data_items.items():
            if key.startswith("mtp_headImage_") and "fields" in value:
                image_fields = value["fields"]
                item_img_urls = image_fields.get("itemImgUrls", [])
                break
                
        # 查找用户评价
        for key, value in data_items.items():
            if key.startswith("mtp_goodsEvaluate_") and "fields" in value:
                evaluate_fields = value["fields"]
                comments = evaluate_fields.get("comments", [])
                break
                
        # 查找推广信息
        for key, value in data_items.items():
            if key.startswith("mtp_popularizeChart_") and "fields" in value:
                popularize_fields = value["fields"]
                promote_info = popularize_fields.get("promoteInfo", {})
                break
                
        # 查找视频列表
        for key, value in data_items.items():
            if key.startswith("mtp_videoList_") and "fields" in value:
                video_fields = value["fields"]
                video_list = video_fields.get("videoList", [])
                break
                
        # 查找同店推荐商品
        for key, value in data_items.items():
            if key.startswith("mtp_merchantsPromotion_") and "fields" in value:
                merchant_fields = value["fields"]
                top_item_list = merchant_fields.get("topItemList", [])
                break
                
        # 缓存结果
        try:
            _detail_cache[self.rel_item_id] = data
        except Exception:
            pass
        # 更新UI
        self.title_label.setText(item_title)
        self.price_label.setText(f"价格: ¥{int(zk_final_price)/100 if zk_final_price else '--'}")
        self.commission_label.setText(f"佣金比例: {commission_rate}%")
        self.profit_label.setText(f"赚取: ¥{profit_amount}")
        self.sales_label.setText(f"总销量: {total_sale_amount}")
        self.shop_label.setText(f"店铺: {shop_name}")
        self.shop_score_label.setText(f"店铺评分: {shop_score}")
        
        # 设置商品详情
        detail_content = f"商品标题: {item_title}\n\n"
        detail_content += f"价格: ¥{int(zk_final_price)/100 if zk_final_price else '--'}\n"
        if reserve_price and reserve_price != zk_final_price:
            detail_content += f"原价: ¥{int(reserve_price)/100 if reserve_price else '--'}\n"
        detail_content += f"佣金比例: {commission_rate}%\n"
        detail_content += f"赚取金额: ¥{profit_amount}\n"
        detail_content += f"总销量: {total_sale_amount}\n"
        detail_content += f"店铺名称: {shop_name}\n"
        detail_content += f"店铺评分: {shop_score}\n"
        self.detail_text.setText(detail_content)
        
        # 设置推广数据
        if promote_info:
            promote_content = f"近30天推广数据:\n"
            promote_content += f"总订单数: {promote_info.get('totalOrderNum', '--')}\n"
            promote_content += f"总浏览量: {promote_info.get('totalPv', '--')}\n"
            promote_content += f"总推广人数: {promote_info.get('totalPromoterNum', '--')}\n\n"
            promote_content += "推广趋势:\n"
            
            promote_list = promote_info.get("promoteList", [])
            for promote_data in promote_list:
                date_str = promote_data.get("dateStr", "")
                order_num = promote_data.get("orderNum", "")
                pv = promote_data.get("pv", "")
                promoter_num = promote_data.get("promoterNum", "")
                promote_content += f"  {date_str}: 订单{order_num} 浏览{pv} 推广{promoter_num}\n"
                
            self.promotion_text.setText(promote_content)
        else:
            self.promotion_text.setText("暂无推广数据")
            
        # 设置用户评价
        self.review_list.clear()
        for comment in comments:
            comment_item = QListWidgetItem()
            username = comment.get('commentUserName', '匿名用户')
            content = comment.get('content', '')
            comment_text = f"{username}: {content}"
            comment_item.setText(comment_text)
            self.review_list.addItem(comment_item)
            
        # 设置视频带货列表
        self.video_list.clear()
        for video in video_list:
            video_item = QListWidgetItem()
            video_widget = QWidget()
            video_layout = QVBoxLayout(video_widget)
            video_layout.setSpacing(10)
            
            # 视频封面（可点击播放）
            video_img_url = video.get('imgUrl', '')
            video_url = video.get('videoUrl', '')
            
            if video_img_url and video_url:
                # 创建可点击的视频封面标签
                video_label = ClickableLabel(video_url)
                video_label.setFixedSize(320, 240)  # 增大视频封面尺寸
                video_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
                video_label.setStyleSheet("""
                    QLabel {
                        background-color: #f8f9fa;
                        border-radius: 12px;
                        font-size: 18px;
                        color: #6c757d;
                        border: 2px dashed #0d6efd;
                    }
                    QLabel:hover {
                        border: 2px solid #0d6efd;
                        background-color: #e7f1ff;
                        font-weight: bold;
                    }
                """)
                video_label.setText("▶ 点击播放视频")
                video_label.clicked.connect(self.play_video)
                video_layout.addWidget(video_label)
                
                # 加载视频封面图片
                self.load_image_from_url(video_img_url, video_label)
            elif video_url:
                # 如果没有封面图片，至少提供可点击的播放区域
                video_label = ClickableLabel(video_url)
                video_label.setFixedSize(320, 240)
                video_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
                video_label.setStyleSheet("""
                    QLabel {
                        background-color: #f8f9fa;
                        border-radius: 12px;
                        font-size: 18px;
                        color: #0d6efd;
                        border: 2px dashed #0d6efd;
                    }
                    QLabel:hover {
                        border: 2px solid #0d6efd;
                        background-color: #e7f1ff;
                        font-weight: bold;
                    }
                """)
                video_label.setText("▶ 点击播放视频")
                video_label.clicked.connect(self.play_video)
                video_layout.addWidget(video_label)
            
            # 视频信息容器
            info_container = QWidget()
            info_container.setStyleSheet("margin-top: 8px;")
            info_layout = QHBoxLayout(info_container)
            info_layout.setContentsMargins(0, 0, 0, 0)
            info_layout.setSpacing(10)
            
            # 视频作者和信息
            author_info = f"{video.get('nikename', '未知作者')}"
            author_label = QLabel(author_info)
            author_label.setStyleSheet("font-weight: bold; font-size: 15px; color: #343a40;")
            info_layout.addWidget(author_label)
            
            # 粉丝数
            fans_label = QLabel(f"粉丝: {video.get('fansNum', '--')}")
            fans_label.setStyleSheet("font-size: 14px; color: #6c757d;")
            info_layout.addWidget(fans_label)
            
            # GMV
            gmv_label = QLabel(f"90天GMV: {video.get('gmvOf90', '--')}")
            gmv_label.setStyleSheet("font-size: 14px; color: #198754; font-weight: bold;")
            info_layout.addWidget(gmv_label)
            
            info_layout.addStretch()
            video_layout.addWidget(info_container)
            
            # 视频统计数据
            stats_container = QWidget()
            stats_layout = QHBoxLayout(stats_container)
            stats_layout.setContentsMargins(0, 0, 0, 0)
            stats_layout.setSpacing(15)
            
            like_label = QLabel(f"👍 {video.get('likeCount', '--')}")
            like_label.setStyleSheet("font-size: 14px; color: #dc3545; font-weight: bold;")
            stats_layout.addWidget(like_label)
            
            comment_label = QLabel(f"💬 {video.get('commentCount', '--')}")
            comment_label.setStyleSheet("font-size: 14px; color: #0d6efd; font-weight: bold;")
            stats_layout.addWidget(comment_label)
            
            share_label = QLabel(f"↗️ {video.get('shareCount', '--')}")
            share_label.setStyleSheet("font-size: 14px; color: #6f42c1; font-weight: bold;")
            stats_layout.addWidget(share_label)
            
            stats_layout.addStretch()
            video_layout.addWidget(stats_container)
            
            video_widget.setLayout(video_layout)
            video_item.setSizeHint(video_widget.sizeHint())
            self.video_list.addItem(video_item)
            self.video_list.setItemWidget(video_item, video_widget)
            
        # 设置同店推荐商品
        self.recommend_list.clear()
        for item in top_item_list:
            item_item = QListWidgetItem()
            item_widget = QWidget()
            item_layout = QHBoxLayout(item_widget)
            item_layout.setSpacing(15)
            
            # 商品标题
            title_label = QLabel(item.get('itemTitle', ''))
            title_label.setStyleSheet("font-weight: bold; font-size: 15px; color: #343a40;")
            item_layout.addWidget(title_label)
            
            # 商品价格
            price_info = f"价格: ¥{item.get('itemPrice', '--')}"
            price_label = QLabel(price_info)
            price_label.setStyleSheet("color: #dc3545; font-weight: bold; font-size: 16px;")
            item_layout.addWidget(price_label)
            
            item_layout.addStretch()
            item_widget.setLayout(item_layout)
            item_item.setSizeHint(item_widget.sizeHint())
            self.recommend_list.addItem(item_item)
            self.recommend_list.setItemWidget(item_item, item_widget)
            
        # 加载图片
        if item_img_urls:
            # 加载主图
            main_image_url = item_img_urls[0] if item_img_urls else ""
            if main_image_url:
                self.load_image_from_url(main_image_url, self.main_image_label)
                
            # 加载缩略图
            self.thumbnail_list.clear()
            for i, img_url in enumerate(item_img_urls[:10]):  # 最多显示10张缩略图
                thumb_item = QListWidgetItem()
                thumb_widget = QWidget()
                thumb_layout = QHBoxLayout(thumb_widget)
                thumb_layout.setContentsMargins(0, 0, 0, 0)
                
                thumb_label = ClickableLabel(img_url)  # 使缩略图可点击
                thumb_label.setFixedSize(60, 60)
                thumb_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
                thumb_label.setStyleSheet("background-color: white; border-radius: 6px; font-size: 10px; color: #6c757d; border: 1px solid #e9ecef;")
                thumb_label.setText("加载中...")
                thumb_label.clicked.connect(self.switch_main_image)
                thumb_layout.addWidget(thumb_label)
                thumb_widget.setLayout(thumb_layout)
                
                thumb_item.setSizeHint(thumb_widget.sizeHint())
                self.thumbnail_list.addItem(thumb_item)
                self.thumbnail_list.setItemWidget(thumb_item, thumb_widget)
                
                # 加载缩略图
                self.load_image_from_url(img_url, thumb_label)
                
    def load_image_from_url(self, image_url, label):
        """异步加载图片，避免阻塞UI"""
        try:
            # 检查全局图片缓存
            global _image_cache
            if image_url in _image_cache:
                # 直接使用缓存的图片
                cached_pixmap = _image_cache[image_url]
                # 缩放到标签大小，保持宽高比
                scaled_pixmap = cached_pixmap.scaled(
                    label.width(), 
                    label.height(),
                    Qt.AspectRatioMode.KeepAspectRatio,
                    Qt.TransformationMode.SmoothTransformation
                )
                label.setPixmap(scaled_pixmap)
                label.setText("")
                return
            
            # 检查是否已经有相同URL的加载请求在进行
            global _loading_urls
            if not hasattr(self, '_loading_urls'):
                self._loading_urls = set()
                
            if image_url in self._loading_urls:
                # 如果已经在加载，等待其完成
                label.setText("图片加载中...")
                return
                
            # 记录当前加载的URL
            self._loading_urls.add(image_url)
            label.setText("图片加载中...")
            
            # 使用异步线程加载图片，避免阻塞UI线程
            from PyQt5.QtCore import QThread, pyqtSignal
            import urllib.request
            import ssl
            
            class ImageLoader(QThread):
                image_loaded = pyqtSignal(object, str)  # QPixmap, URL
                error_occurred = pyqtSignal(str, str)  # error_msg, URL
                
                def __init__(self, url):
                    super().__init__()
                    self.url = url
                    
                def run(self):
                    try:
                        # 创建不验证SSL证书的上下文（仅用于测试环境）
                        context = ssl.create_default_context()
                        context.check_hostname = False
                        context.verify_mode = ssl.CERT_NONE
                        
                        # 使用urllib下载图片数据
                        headers = {
                            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
                        }
                        req = urllib.request.Request(self.url, headers=headers)
                        response = urllib.request.urlopen(req, context=context, timeout=10)  # 减少超时时间
                        image_data = response.read()
                        
                        # 创建QImage
                        from PyQt5.QtGui import QImage, QPixmap
                        image = QImage()
                        image.loadFromData(image_data)
                        
                        if not image.isNull():
                            # 转换为QPixmap并加入缓存
                            pixmap = QPixmap.fromImage(image)
                            self.image_loaded.emit(pixmap, self.url)
                        else:
                            self.error_occurred.emit("图片加载失败", self.url)
                    except Exception as e:
                        self.error_occurred.emit(str(e), self.url)
                    
                def __del__(self):
                    # 确保线程正确退出
                    if self.isRunning():
                        self.quit()
                        self.wait()
            
            # 创建并启动图片加载线程
            if not hasattr(self, '_image_loader'):
                self._image_loader = {}
                
            loader = ImageLoader(image_url)
            self._image_loader[image_url] = loader
            # 添加到活动加载器列表
            self.active_image_loaders.append(loader)
            # 使用weakref避免循环引用
            import weakref
            loader.image_loaded.connect(lambda pixmap, url: self.on_image_loaded(pixmap, url, label))
            loader.error_occurred.connect(lambda error_msg, url: self.on_image_error(error_msg, url, label))
            loader.start()
        except Exception as e:
            print(f"启动图片加载失败: {str(e)}")
            label.setText("加载失败")
            
    def on_image_loaded(self, pixmap, url, label):
        """图片加载完成回调"""
        # 清理加载状态
        if hasattr(self, '_loading_urls') and url in self._loading_urls:
            self._loading_urls.remove(url)
            
        # 从加载器字典中移除
        if hasattr(self, '_image_loader') and url in self._image_loader:
            del self._image_loader[url]
            
        # 缩放到标签大小，保持宽高比
        scaled_pixmap = pixmap.scaled(
            label.width(), 
            label.height(),
            Qt.AspectRatioMode.KeepAspectRatio,
            Qt.TransformationMode.SmoothTransformation
        )
        
        # 显示图片
        label.setPixmap(scaled_pixmap)
        label.setText("")
        
        # 加入全局缓存
        global _image_cache, _image_cache_max_size
        _image_cache[url] = pixmap
        
        # 检查缓存大小，如果超过限制则清理老的缓存
        if len(_image_cache) > _image_cache_max_size:
            # 删除最老的缓存项目
            oldest_key = next(iter(_image_cache))
            del _image_cache[oldest_key]
        
    def on_image_error(self, error_msg, url, label):
        """图片加载错误回调"""
        # 清理加载状态
        if hasattr(self, '_loading_urls') and url in self._loading_urls:
            self._loading_urls.remove(url)
            
        # 从加载器字典中移除
        if hasattr(self, '_image_loader') and url in self._image_loader:
            del self._image_loader[url]
            
        print(f"加载图片失败: {error_msg}")
        # 显示错误信息
        label.setText("加载失败")
            
    def close_window(self):
        """关闭窗口"""
        self.close()
        
    def switch_main_image(self, image_url):
        """切换主图"""
        self.main_image_label.setText("主图切换中...")
        self.load_image_from_url(image_url, self.main_image_label)
        
    def play_video(self, video_url):
        """在浏览器中播放视频"""
        if video_url:
            try:
                # 直接在浏览器中打开视频链接
                webbrowser.open(video_url)
            except Exception as e:
                # 如果无法打开视频链接，显示错误信息
                QMessageBox.warning(self, "播放失败", f"无法打开视频链接: {str(e)}")
        else:
            QMessageBox.warning(self, "播放失败", "视频链接为空")
        
    def on_error(self, error_msg):
        print(f"错误: {error_msg}")
        self.title_label.setText(f"加载失败: {error_msg}")
        
    def closeEvent(self, a0):
        """窗口关闭事件"""
        # 清理所有活动的图片加载线程
        for loader in self.active_image_loaders:
            if loader.isRunning():
                loader.quit()
                loader.wait()
        self.active_image_loaders.clear()
        super().closeEvent(a0)

# 主函数
def show_product_detail(rel_item_id):
    app = QApplication(sys.argv)
    window = ProductDetailWindow(rel_item_id)
    window.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    # 示例：显示商品详情，需要传入relItemId参数
    # 示例relItemId: "23099312035279"
    if len(sys.argv) > 1:
        rel_item_id = sys.argv[1]
    else:
        rel_item_id = "23099312035279"  # 默认示例ID
    show_product_detail(rel_item_id)